
// 产品模块
const sequelize = require('../config/operateDB');
const {Sequelize, DataTypes, Op} = require('sequelize');


const Companies = sequelize.define('companys', {
    id: {
        type: DataTypes.UUID,
        allowNull: false,
        primaryKey: true,
        defaultValue: Sequelize.UUIDV4,
    },
    name: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    creator: {
        type: DataTypes.UUID,
        allowNull: false,
    },
    logoUrl: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    description: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    marks: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    cratorName: {
        type: DataTypes.TEXT,
        allowNull: true,
    }
}, {

});

async function getCount() {
    await Companies.sync();
    const count = await Companies.count();
    if (0 === count) {
        await Companies.create({
            id: 'a0a53019-820d-4253-8338-0e6fb09a5e7b',
            name: '管理员单位',
            logoUrl: '/images/defaultCompany.jpg',
            marks: '10',
            description: '管理员用户',
            cratorName: '管理员',
            creator: '6e81b384-dce5-4d58-abf9-56bde96eda25',
            
        });

        console.log('初始化单位成功！');
    }
}
getCount();




const companiesModel = {
    async getCompany(ctx) {
        const params = ctx.query;
        // const count = await Companies.count();
        const {offset = 0, limit = 10, keywords = ''} = params;
        const { count, rows } = await Companies.findAndCountAll(
            {
                where: {
                    name: {
                        [Op.like]: '%' + keywords + '%',
                    },
                },
                limit: parseInt(limit),
                offset: parseInt(offset),
                raw: true,
            }
        );
        ctx.pageRes({
            limit,
            offset,
            list: rows,
            total: count,
        });
    },

    async addCompany(ctx) {
        const params = ctx.request.body;
        const validFlag = this.validCompany(ctx, params);
        if (validFlag) {
            const poducts = await Companies.create({
                name: params.name,
                logoUrl: params.logoUrl,
                marks: '10',
                description: params.description,
                cratorName: params.cratorName,
                creator: ctx.session.sessionData.id,
            });

            ctx.success('增加成功！', poducts);
        }
    },
    validCompany(ctx, params) {
        if (!params.name) {
            ctx.errorParams('公司名称不存在！');
            return false;
        } else if (!params.logoUrl) {
            ctx.errorParams('公司logo不存在！');
            return false;
        } else {
            return true;
        }
    },
    async deleteCompanies(ctx)  {
        const {User} = require('./users');
        if (!!ctx.request.body.id) {
            const deleteIds = (ctx.request.body.id || '').split(',');
            const users = await User.findAll({
                where: {
                    company: {
                        [Op.in]: deleteIds
                    }
                },
                raw: true,
            });
            if (0 !== users.length) {
                ctx.serviceError('当前单位下存在用户！', null);
                return ;
            }

            const delCompanies = await Companies.destroy({
                where: {
                    id: {
                        [Op.in]: deleteIds,
                    },
                },
            });
            if (0 === delCompanies) {
                ctx.errorParams('未找到指定id！');
            } else {
                ctx.success('删除成功！', {
                    id: deleteIds,
                });
            }

            
        } else {
            ctx.errorParams('id不存在！');
        }
    },
    async editCompany(ctx)  {
        const params = ctx.request.body;
        const editId = params.id;
        if (!editId) {
            ctx.errorParams('id不存在！');
        } else {
            // 
            const company = await Companies.findOne({
                where: {
                    id: editId
                },
                raw: true,
            });
            await Companies.update({
                ...company,
                ...params,
            }, {
                where: {
                    id: editId
                },
            });
            ctx.success('修改成功', {
                id: editId,
            });
        }
        
    },
    async companyInfo(ctx) {
        const params = ctx.query;
        const id = params.id;
        const {User} = require('./users');
        if (!!id) {
            const users = await User.count({
                where: {
                    company: id
                },
                raw: true,
            });
            const count = await User.count();
    
            const company = await Companies.findOne({
                where: {
                    id: id
                },
                raw: true,
            });
            ctx.success('公司信息查询成功', {
                companyUsers: users,
                userCount: count,
                marks: company.marks
            })
        } else {
            ctx.errorParams('传参数呀，小伙子！')
        }
        
    }
    
};


module.exports = {
    companiesModel,
    Companies
};